package cn.chair.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {
	
    private static final Logger elog = LoggerFactory.getLogger("errorLogger");

	@Bean(destroyMethod="close")
	@Primary
	public DataSource dataSource(@Value("${datasource.driver-class-name}") String driver,
                                 @Value("${datasource.url}") String url,
                                 @Value("${datasource.username}") String username,
                                 @Value("${datasource.password}") String password) {
		return createDataSource(driver, url, username, password);
	}

    @Bean(name="tempDateSource", destroyMethod="close")
    public DataSource tempDataSource(@Value("${datasource.temp.driver-class-name}") String driver,
                                     @Value("${datasource.temp.url}") String url,
                                     @Value("${datasource.temp.username}") String username,
                                     @Value("${datasource.temp.password}") String password) {
        return createDataSource(driver, url, username, password);
    }

	private DataSource createDataSource(String driver, String url, String username, String password) {
		try {
			ComboPooledDataSource ds = new ComboPooledDataSource();
			ds.setDriverClass(driver);
			ds.setJdbcUrl(url);
			ds.setUser(username);
			ds.setPassword(password);
			ds.setInitialPoolSize(3);
			ds.setAcquireIncrement(5);
			ds.setIdleConnectionTestPeriod(60);
			ds.setMaxPoolSize(100);
			ds.setMaxStatements(50);
			ds.setMinPoolSize(10);
			
			return ds;
		} catch (Exception e) {
            elog.error("Failed to obtain data source: " + e.getMessage());
			throw new RuntimeException(e);
		}
	}
}
